import { ref, reactive, computed } from "vue";
import { toast } from "@/composables/util";

//列表，分页，搜索，删除，修改状态
export function useInitTable(opt = {}) {
  let searchform = null
  let resetSearchform = null
  if (opt.searchform) {
    //创建响应式搜索表单，初始值来自opt.searchform--将普通对象转化为响应式对象，保留初始值，用于重置表单
    searchform = reactive({ ...opt.searchform })
    //重置搜索表单方法
    resetSearchform = () => {
      for (const key in opt.searchform) {
        searchform[key] = opt.searchform[key]; //恢复初始值
      }
      getData(); //重置后刷新数据
    };
  }

  const tableData = ref([]);
  const loading = ref(false);
  const currentPage = ref(1); //当前页码
  const total = ref(0); //分类总数--多少条
  const limit = ref(10); //每页显示量

  //获取最新数据
  function getData(p = null) {
    if (typeof p == "number") {
      //p默认值为null 为数字类型说明有传页码过来
      currentPage.value = p; //拿到最新的页码
    }

    loading.value = true;
    //动态传参--getList获取不同的API接口函数
    opt
      .getList(currentPage.value, searchform)
      .then((res) => {
        if (opt.onGetListSuccess && typeof opt.onGetListSuccess == "function") {
          //onGetListSuccess是请求成功后的回调函数，用于自定义处理返回数据
          opt.onGetListSuccess(res);
        } else {
          tableData.value = res.list;
          total.value = res.totalCount;
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
  getData();

  //删除
  const handleDelete = (id) => {
    loading.value = true;
    opt
      .delete(id)
      .then((res) => {
        toast("删除成功");
        getData();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //修改状态--$event是获取到即将变化的数值
  const handleStatusChange = (status, row) => {
    row.statusloading = true;
    opt
      .updateStatus(row.id, status)
      .then((res) => {
        toast("修改状态成功");
        row.status = status;
      })
      .finally(() => {
        row.statusloading = false;
      });
  };


  

  //多选选中id
  const multiSelections = ref([]);
  const handleSelectionChange = (e) => {
    multiSelections.value = e.map((o) => o.id)
  }

  //批量删除,区分一下内部的接口
  const multipleTableRef = ref(null);
  const handleMultiDelete = () => {
    loading.value = true;
    opt.delete(multiSelections.value)
      .then((res) => {
        toast("批量删除成功")
        //清空选中
        if (multipleTableRef.value) {
          multipleTableRef.value.clearSelection();
        }
        getData();
      })
      .finally(() => {
        loading.value = false;
      })
  }


  //批量修改状态
   const handleMultiStatusChange = (status) => {
    loading.value = true;
    opt.updateStatus(multiSelections.value,status)
      .then((res) => {
        toast("批量修改成功")
        //批量修改选中
        if (multipleTableRef.value) {
          multipleTableRef.value.clearSelection();
        }
        getData();
      })
      .finally(() => {
        loading.value = false;
      })
  }  


  return {
    searchform, //搜索表单数据
    resetSearchform, //重置搜索表单的方法
    tableData, //表格数据
    loading, //加载状态
    currentPage, //当前页码
    total, //总记录数
    limit, //每页显示量
    getData, //刷新数据的方法
    handleDelete,
    handleStatusChange,
    handleSelectionChange, //给选中的对象添加id
    multipleTableRef, //选中对象的内容
    handleMultiDelete,  //批量删除方法
    handleMultiStatusChange, //批量修改
    multiSelections
  };
}

//新增和修改
export function useInitForm(opt = {}) {
  //表单部分
  const formDrawerRef = ref(null);
  const formRef = ref(null);
  const form = reactive({}); //动态数据--其他模块的表单不一样，也需要动态传参
  const defaultForm = opt.form; //给予表单默认值--静态模板
  const rules = opt.rules || {};
  const edit = ref(0); //等于0代表新增，等于当前对象id代表修改
  const drawerTitle = computed(() => (edit.value ? "修改" : "新增"));

  //提交事件--修改数据库的内容--验证
  const handleSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) return;

      formDrawerRef.value.showloading();

      //在优惠卷接口文档--内容需要是时间戳的形式才可以传回去，因此做出判断
      let body = {}
      if(opt.beforSubmit && typeof opt.beforSubmit == "function"){
        body = opt.beforSubmit({...form})
      } else{
        body = form
      }

      //接口方法运用到其他模块是不一样的，所以要动态传参
      const fun = edit.value ? opt.update(edit.value, body) : opt.create(body);
      fun
        .then((res) => {
          toast(drawerTitle.value + "成功");
          opt.getData(edit.value ? false : 1); //修改刷新当前页--false是当前页，新增刷新第一页
          formDrawerRef.value.close();
        })
        .finally(() => {
          formDrawerRef.value.hideloading();
        });
    });
  };

  //重置表单--初始化表单数据/基于现有数据预填充表单
  function resetForm(row = false) {
    //此处的判断条件是为了确保表单组件已经被挂载完成，与传入的数据无关
    if (formRef.value) formRef.value.clearValidate(); //重置校验状态，确保用户看到干净的输入状态
    for (const key in defaultForm) {
      form[key] = row[key] || defaultForm[key];
    }
  }

  //新增
  const handleCreate = () => {
    edit.value = 0;
    resetForm(defaultForm);
    formDrawerRef.value.open();
  };

  //编辑
  const handleEdit = (row) => {
    edit.value = row.id;
    resetForm(row);
    formDrawerRef.value.open();
  };

  return {
    formDrawerRef,
    formRef,
    form,
    rules,
    edit,
    drawerTitle,
    handleSubmit,
    resetForm,
    handleCreate,
    handleEdit,
  };
}
